﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BeginInvokeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             * 对异步委托进行控制：
             * 1.  EndInvoke
             * 2.  AsyncCallback委托， 在异步委托完成后会执行该委托
             * 3.  AsyncWaitHandle.WaitOne(1000)，等待1000ms，如果提前执行完就往下执行，
             *                                                1000ms后异步委托没执行玩也继续往下执行
             * 4. IsCompleted
             * 
             * 
             * **/
            Func<int, int> func = MyTest;
            // 2.1.1
            //AsyncCallback asyncCallback = iar => { Console.WriteLine("子线程："+Thread.CurrentThread.ManagedThreadId+" 执行完毕"); };
            // 2.1.2
            //IAsyncResult ar = func.BeginInvoke(10, asyncCallback, null);

            // 2.2 直接用lambda表达式写AsyncCallback委托
            IAsyncResult ar = func.BeginInvoke(10,
                                               iar => { Console.WriteLine("子线程：" + Thread.CurrentThread.ManagedThreadId + " 执行完毕"); },
                                               null);
            //int result = func.EndInvoke(ar);     // 1

            //ar.AsyncWaitHandle.WaitOne(1000);    // 3
            Console.WriteLine("主线程："+Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("主线程：" + Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("主线程：" + Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("主线程：" + Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("主线程：" + Thread.CurrentThread.ManagedThreadId);

            //Console.WriteLine("全部计算完成，结果为：" + result);
            //Thread.Sleep(2000);

            // 4
            int i = 0;
            while(!ar.IsCompleted)
            {
                if(i<10)
                {
                    Console.WriteLine("执行进度："+i++*10+"%");
                }
                else
                {
                    Console.WriteLine("执行进度：99.9%");
                }
                Thread.Sleep(200);
            }
            Console.WriteLine("全部计算完成");
            while (true) ;
        }

        static public int MyTest(int a)
        {
            Console.WriteLine("子线程："+Thread.CurrentThread.ManagedThreadId+"，开始");
            for(int i=0;i<1000000000;i++)
            {
                a++;
            }
            Console.WriteLine("子线程：" + Thread.CurrentThread.ManagedThreadId + "，结束");
            Console.WriteLine("结果："+a);
            return a;
        }
    }
}
